package com.bw.curl.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.curl.dao.PmsCategoryMapper;
import com.bw.curl.entity.PmsCategory;
import com.bw.curl.service.PmsCategoryService;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品三级分类 服务实现类
 * </p>
 *
 * @author Zeng
 * @since 2023-10-28
 */
@Service
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryMapper, PmsCategory> implements PmsCategoryService {


    /**
     * @return {@link List}<{@link PmsCategory}>
     */
    @Override
    public List<PmsCategory> listWithTree() {
        //1、查出所有分类
        List<PmsCategory> entities = baseMapper.selectList(null);
        //2、组装成父子的树形结构
        //2.1）、找到所有的一级分类
        List<PmsCategory> level1Menus = entities.stream().filter(
                //一级分类的parentId=0,根据这个条件构建出一级分类的数据
                categoryEntity -> categoryEntity.getParentCid().equals(NumberUtils.INTEGER_ZERO.toString())
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    /**
     * 递归查找所有菜单的子菜单
     * @param root
     * @param all
     * @return {@link List}<{@link PmsCategory}>
     */
    private List<PmsCategory> getChildrens(PmsCategory root,List<PmsCategory> all){
        return all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2、菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
    }


}
